<template>
  <div class="emails-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Message /></el-icon>
          <div class="header-text">
            <h2>邮件管理</h2>
            <p>企业邮件收发管理</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showComposeDialog = true">
            <el-icon><Plus /></el-icon>
            写邮件
          </el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20">
      <!-- 左侧邮箱文件夹 -->
      <el-col :span="4">
        <el-card shadow="never" class="folder-card">
          <el-menu :default-active="currentFolder" @select="handleFolderChange">
            <el-menu-item index="inbox">
              <el-icon><Message /></el-icon>
              <span>收件箱</span>
              <el-badge :value="unreadCount.inbox" :hidden="unreadCount.inbox === 0" class="badge" />
            </el-menu-item>
            <el-menu-item index="sent">
              <el-icon><Position /></el-icon>
              <span>已发送</span>
            </el-menu-item>
            <el-menu-item index="draft">
              <el-icon><Edit /></el-icon>
              <span>草稿箱</span>
              <el-badge :value="unreadCount.draft" :hidden="unreadCount.draft === 0" class="badge" />
            </el-menu-item>
            <el-menu-item index="starred">
              <el-icon><StarFilled /></el-icon>
              <span>星标邮件</span>
            </el-menu-item>
            <el-menu-item index="trash">
              <el-icon><Delete /></el-icon>
              <span>已删除</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>

      <!-- 中间邮件列表 -->
      <el-col :span="8">
        <el-card shadow="never" class="email-list-card">
          <div class="list-header">
            <el-input
              v-model="searchText"
              placeholder="搜索邮件"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <div class="list-actions">
              <el-button @click="handleRefresh" circle>
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </div>

          <div class="email-list">
            <div
              v-for="email in filteredEmails"
              :key="email.id"
              :class="['email-item', { 'active': currentEmail?.id === email.id, 'unread': !email.isRead }]"
              @click="handleEmailClick(email)"
            >
              <div class="email-item-header">
                <div class="sender">
                  <el-icon class="star-icon" @click.stop="handleToggleStar(email)">
                    <StarFilled v-if="email.starred" style="color: #F7BA2A;" />
                    <Star v-else />
                  </el-icon>
                  <span class="sender-name">{{ email.from }}</span>
                </div>
                <span class="email-time">{{ email.time }}</span>
              </div>
              <div class="email-subject">{{ email.subject }}</div>
              <div class="email-preview">{{ email.preview }}</div>
              <div class="email-footer">
                <el-tag v-if="email.hasAttachment" size="small" type="info">
                  <el-icon><Paperclip /></el-icon>
                  附件
                </el-tag>
              </div>
            </div>
          </div>

          <el-empty v-if="filteredEmails.length === 0" description="暂无邮件" />
        </el-card>
      </el-col>

      <!-- 右侧邮件详情 -->
      <el-col :span="12">
        <el-card shadow="never" class="email-detail-card">
          <div v-if="currentEmail" class="email-detail">
            <div class="detail-header">
              <h3 class="detail-subject">{{ currentEmail.subject }}</h3>
              <div class="detail-actions">
                <el-button @click="handleReply">
                  <el-icon><Back /></el-icon>
                  回复
                </el-button>
                <el-button @click="handleForward">
                  <el-icon><Right /></el-icon>
                  转发
                </el-button>
                <el-button type="danger" @click="handleDeleteEmail">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </div>

            <el-divider />

            <div class="detail-info">
              <div class="info-row">
                <span class="info-label">发件人：</span>
                <span class="info-value">{{ currentEmail.from }} &lt;{{ currentEmail.fromEmail }}&gt;</span>
              </div>
              <div class="info-row">
                <span class="info-label">收件人：</span>
                <span class="info-value">{{ currentEmail.to }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">时间：</span>
                <span class="info-value">{{ currentEmail.fullTime }}</span>
              </div>
            </div>

            <el-divider />

            <div class="detail-content">
              <div v-html="currentEmail.content"></div>
            </div>

            <div v-if="currentEmail.attachments && currentEmail.attachments.length > 0" class="detail-attachments">
              <el-divider />
            <div class="attachments-title">
              <el-icon><Document /></el-icon>
              附件 ({{ currentEmail.attachments.length }})
            </div>
              <div class="attachments-list">
                <div
                  v-for="(file, index) in currentEmail.attachments"
                  :key="index"
                  class="attachment-item"
                >
                  <el-icon><Document /></el-icon>
                  <span class="file-name">{{ file.name }}</span>
                  <span class="file-size">{{ file.size }}</span>
                  <el-button link type="primary" @click="handleDownloadAttachment(file)">
                    <el-icon><Download /></el-icon>
                    下载
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <el-empty v-else description="选择一封邮件查看" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 写邮件对话框 -->
    <el-dialog v-model="showComposeDialog" title="写邮件" width="900px" destroy-on-close>
      <el-form :model="composeForm" :rules="composeRules" ref="composeFormRef" label-width="80px">
        <el-form-item label="收件人" prop="to">
          <el-select
            v-model="composeForm.to"
            multiple
            filterable
            allow-create
            placeholder="请输入或选择收件人"
            style="width: 100%"
          >
            <el-option label="张三 <zhangsan@company.com>" value="zhangsan@company.com" />
            <el-option label="李四 <lisi@company.com>" value="lisi@company.com" />
            <el-option label="王五 <wangwu@company.com>" value="wangwu@company.com" />
          </el-select>
        </el-form-item>
        <el-form-item label="抄送">
          <el-select
            v-model="composeForm.cc"
            multiple
            filterable
            allow-create
            placeholder="请输入或选择抄送人（选填）"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="主题" prop="subject">
          <el-input v-model="composeForm.subject" placeholder="请输入邮件主题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="composeForm.content"
            type="textarea"
            :rows="12"
            placeholder="请输入邮件内容"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="#"
            :auto-upload="false"
            multiple
            :on-change="handleAttachmentChange"
            :file-list="composeForm.attachments"
          >
            <el-button>
              <el-icon><Folder /></el-icon>
              选择文件
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showComposeDialog = false">取消</el-button>
        <el-button @click="handleSaveDraft">保存草稿</el-button>
        <el-button type="primary" @click="handleSendEmail">发送</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Message, Plus, Edit, StarFilled, Delete, Search, Refresh,
  Star, Document, Download, Folder, Position, Back, Right
} from '@element-plus/icons-vue'

// 状态
const currentFolder = ref('inbox')
const searchText = ref('')
const currentEmail = ref(null)

// 未读数量
const unreadCount = reactive({
  inbox: 5,
  draft: 2
})

// 对话框
const showComposeDialog = ref(false)
const composeFormRef = ref(null)

// 表单
const composeForm = reactive({
  to: [],
  cc: [],
  subject: '',
  content: '',
  attachments: []
})

// 表单验证规则
const composeRules = {
  to: [{ required: true, message: '请输入收件人', trigger: 'change' }],
  subject: [{ required: true, message: '请输入邮件主题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入邮件内容', trigger: 'blur' }]
}

// 邮件数据
const emails = ref([
  {
    id: 1,
    folder: 'inbox',
    from: '张三',
    fromEmail: 'zhangsan@company.com',
    to: '我',
    subject: '关于项目进度的讨论',
    preview: '您好，我想和您讨论一下当前项目的进度情况...',
    content: '<p>您好，</p><p>我想和您讨论一下当前项目的进度情况，希望能在本周内完成第一阶段的开发工作。</p><p>请查看附件中的详细计划。</p><p>谢谢！</p>',
    time: '10:30',
    fullTime: '2024-01-15 10:30:25',
    isRead: false,
    starred: false,
    hasAttachment: true,
    attachments: [
      { name: '项目计划.docx', size: '2.5 MB' }
    ]
  },
  {
    id: 2,
    folder: 'inbox',
    from: '李四',
    fromEmail: 'lisi@company.com',
    to: '我',
    subject: '会议通知：明天下午2点',
    preview: '会议时间：明天下午2点，会议室A...',
    content: '<p>各位同事，</p><p>明天下午2点在会议室A召开月度总结会议，请大家准时参加。</p>',
    time: '09:15',
    fullTime: '2024-01-15 09:15:00',
    isRead: false,
    starred: true,
    hasAttachment: false
  },
  {
    id: 3,
    folder: 'inbox',
    from: '王五',
    fromEmail: 'wangwu@company.com',
    to: '我',
    subject: '报销申请审批',
    preview: '您有一条报销申请需要审批...',
    content: '<p>您好，</p><p>请查看并审批我的报销申请。</p>',
    time: '昨天',
    fullTime: '2024-01-14 16:30:00',
    isRead: true,
    starred: false,
    hasAttachment: false
  },
  {
    id: 4,
    folder: 'sent',
    from: '我',
    fromEmail: 'me@company.com',
    to: '张三',
    subject: '回复：关于项目进度的讨论',
    preview: '好的，我们按计划进行...',
    content: '<p>张三，</p><p>好的，我们按计划进行，我会尽快完成相关工作。</p>',
    time: '昨天',
    fullTime: '2024-01-14 11:00:00',
    isRead: true,
    starred: false,
    hasAttachment: false
  }
])

// 计算属性
const filteredEmails = computed(() => {
  let result = emails.value.filter(email => email.folder === currentFolder.value)
  if (searchText.value) {
    result = result.filter(email =>
      email.subject.includes(searchText.value) ||
      email.from.includes(searchText.value) ||
      email.preview.includes(searchText.value)
    )
  }
  return result
})

// 方法
const handleFolderChange = (folder) => {
  currentFolder.value = folder
  currentEmail.value = null
}

const handleEmailClick = (email) => {
  currentEmail.value = email
  if (!email.isRead) {
    email.isRead = true
    unreadCount[email.folder]--
  }
}

const handleToggleStar = (email) => {
  email.starred = !email.starred
  ElMessage.success(email.starred ? '已加星标' : '已取消星标')
}

const handleRefresh = () => {
  ElMessage.success('刷新成功')
}

const handleReply = () => {
  composeForm.to = [currentEmail.value.fromEmail]
  composeForm.subject = 'Re: ' + currentEmail.value.subject
  composeForm.content = '\n\n\n------- 原始邮件 -------\n' + currentEmail.value.content.replace(/<[^>]+>/g, '')
  showComposeDialog.value = true
}

const handleForward = () => {
  composeForm.to = []
  composeForm.subject = 'Fwd: ' + currentEmail.value.subject
  composeForm.content = '\n\n\n------- 转发邮件 -------\n' + currentEmail.value.content.replace(/<[^>]+>/g, '')
  showComposeDialog.value = true
}

const handleDeleteEmail = () => {
  ElMessageBox.confirm('确定要删除这封邮件吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = emails.value.findIndex(e => e.id === currentEmail.value.id)
    if (index > -1) {
      emails.value[index].folder = 'trash'
    }
    currentEmail.value = null
    ElMessage.success('已删除')
  }).catch(() => {})
}

const handleAttachmentChange = (file, fileList) => {
  composeForm.attachments = fileList
}

const handleSaveDraft = () => {
  ElMessage.success('已保存到草稿箱')
  showComposeDialog.value = false
}

const handleSendEmail = () => {
  composeFormRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('发送成功')
      showComposeDialog.value = false
      // 重置表单
      Object.assign(composeForm, {
        to: [],
        cc: [],
        subject: '',
        content: '',
        attachments: []
      })
    }
  })
}

const handleDownloadAttachment = (file) => {
  ElMessage.success('开始下载：' + file.name)
}
</script>

<style scoped>
.emails-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.folder-card {
  height: calc(100vh - 220px);
}

.badge {
  margin-left: auto;
}

.email-list-card {
  height: calc(100vh - 220px);
  display: flex;
  flex-direction: column;
}

.list-header {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}

.email-list {
  flex: 1;
  overflow-y: auto;
}

.email-item {
  padding: 16px;
  border-bottom: 1px solid #EBEEF5;
  cursor: pointer;
  transition: all 0.3s;
}

.email-item:hover {
  background-color: #f5f7fa;
}

.email-item.active {
  background-color: #ecf5ff;
  border-left: 3px solid #409EFF;
}

.email-item.unread {
  background-color: #f0f9ff;
}

.email-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.sender {
  display: flex;
  align-items: center;
  gap: 8px;
}

.star-icon {
  cursor: pointer;
}

.sender-name {
  font-weight: 500;
}

.email-time {
  font-size: 13px;
  color: #909399;
}

.email-subject {
  font-weight: 500;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.email-preview {
  font-size: 13px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 8px;
}

.email-footer {
  display: flex;
  gap: 8px;
}

.email-detail-card {
  height: calc(100vh - 220px);
  overflow-y: auto;
}

.email-detail {
  padding: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.detail-subject {
  margin: 0;
  font-size: 20px;
  flex: 1;
}

.detail-actions {
  display: flex;
  gap: 8px;
}

.detail-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  font-size: 14px;
}

.info-label {
  color: #909399;
  min-width: 70px;
}

.info-value {
  color: #303133;
}

.detail-content {
  padding: 20px 0;
  line-height: 1.8;
  color: #303133;
}

.detail-attachments {
  margin-top: 20px;
}

.attachments-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  margin-bottom: 12px;
}

.attachments-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.file-name {
  flex: 1;
}

.file-size {
  font-size: 13px;
  color: #909399;
}
</style>

